import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hc_bot_pro/common/tool/datetime_ex.dart';
import 'package:hc_cure_sdk_flutter/model/cure/cure.dart';

import '../service/log/api.dart';
import '../service/sdk_service.dart';

class PlayerRecord {
  late String uuid;
  late String startAt;
  late String endAt;
  late int seconds;
  late int cureID;

  PlayerRecord() {}

  PlayerRecord.fromJson(Map<String, dynamic> json) {
    uuid = json['uuid'];
    startAt = json['startAt'];
    endAt = json['endAt'];
    seconds = json['seconds'];
    cureID = json['cureID'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data['uuid'] = uuid;
    data['startAt'] = startAt;
    data['endAt'] = endAt;
    data['seconds'] = seconds;
    data['cureID'] = cureID;

    return data;
  }
}

extension PlayerRecordSync on PlayerRecord {
  void start(Cure cure) {
    uuid = Get.find<SDKService>().uuid;
    startAt = DateTime.now().formattedString;
    endAt = "";
    seconds = 0;
    cureID = cure.id;
  }

  Future update(Duration duration) async {
    if (duration < 1.minutes || duration.inSeconds - seconds <= 1) return;
    endAt = DateTime.now().formattedString;
    seconds = duration.inSeconds;

    if (duration.inSeconds % 60 != 0) {
      return;
    }
    await Get.find<CurePlayMemoService>().saveRecord(this);
    try {
      await Future.delayed(1.seconds);
      await Get.find<CurePlayMemoService>().sync();
    } catch (e) {
      debugPrint(e.toString());
    }
  }
}
